package com.studorm.action;



import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


import javax.servlet.http.HttpServletRequest;


import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.studorm.Connection_mysql;


public class EditPWAction extends ActionSupport{
		
	private static final long serialVersionUID = -3697921271744988026L;
			private int identity;
	
	public int getIdentity() {
				return identity;
			}

			public void setIdentity(int identity) {
				this.identity = identity;
			}

	public String editPassword() throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest(); 
		String identity_s=request.getParameter("identity");
		String id = request.getParameter("id");
		String oldpw = request.getParameter("oldpw");
		String newpw = request.getParameter("newpw");

		
		
		//HttpServletResponse response = ServletActionContext.getResponse();
		
		if(id == null || id.isEmpty()){
			return ERROR;
		}
		if(oldpw == null || oldpw.isEmpty() || oldpw.length() < 6){
			return ERROR;
		}
		if(newpw == null || newpw.isEmpty() || newpw.length() < 6){
			return ERROR;
		}
		if(identity_s == null | identity_s.isEmpty()){
			return ERROR;
		}
		identity = Integer.parseInt(identity_s);
		
		Connection conn = Connection_mysql.getConnection();
		ResultSet res;
		String sql = null;
		if(identity == 3){
			sql = "SELECT COUNT(*) FROM studentsinf WHERE studentNu = ? and password = MD5(?) ";
		}
		if(identity == 2){
			sql = "SELECT COUNT(*) FROM staffinf WHERE staffNu = ? and password = MD5(?)";
		}
	
		
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1,id);
		ps.setString(2, oldpw);
		res = ps.executeQuery();
		int count = 0;
		while(res.next()){
			count = res.getInt(1);
		}
		res.close();
		ps.close();
		
		if(count == 1){
			
			if(identity == 3){
				sql = "UPDATE studentsinf SET password = MD5(?) WHERE studentNu = ? ";
			}
			if(identity == 2){
				sql = "UPDATE staffinf SET password = MD5(?)  WHERE staffNu = ? ";
			}
			ps=conn.prepareStatement(sql);
			ps.setString(1,newpw);
			ps.setString(2, id);
			
			int res2 = ps.executeUpdate();
			
			ps.close();
			conn.close();
			
			if(res2 < 1){
				return ERROR;
			}else{
				return SUCCESS;
			}
		}
	else{
			//conn.close();
			identity = 0;
		}
		

		return SUCCESS;
	}

}
